package com.syzygy.controller;

import com.alibaba.fastjson2.JSONArray;
import com.syzygy.pojo.Picture;
import com.syzygy.pojo.Type;
import com.syzygy.pojo.User;
import com.syzygy.service.PictureService;
import com.syzygy.service.TypeService;
import com.syzygy.service.UserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import util.CookieUtils;
import util.PictureUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/User")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private PictureService pictureService;
    @Autowired
    private PictureUtils pictureUtils;
    @Autowired
    private TypeService typeService;


    //    用户创建页面
    @RequestMapping("/Create")
    protected String userCreate() {
        return "userCreateCard";
    }


    //    用户登录页面
    @RequestMapping("/Login")
    protected String userLogin() {
        return "userLoginCard";
    }


    //    根据userId查User
    @RequestMapping(value = "/{userId}", method = RequestMethod.GET)
    @ResponseBody
    public User getUserByUserId(@PathVariable int userId) {
        return userService.getUserByUserId(userId);
    }


    //    创建新用户
    @RequestMapping(value = "/", method = RequestMethod.POST)
    public String createUser(@RequestParam("file") MultipartFile file,
                             @RequestParam("username") String username,
                             @RequestParam("password") String password,
                             @RequestParam("nickname") String nickname,
                             @RequestParam("phone") int phone,
                             @RequestParam("personalIntroduction") String personalIntroduction

    ) throws IOException {
        if (null != file) {
//        图片id
            String headSculptureId = pictureUtils.getPictureId();
//        图片路径前缀
            String headSculptureUrlPrefix = "D:/Syzygy/headsculpture/";
//        获取图片类型
            // 2 获取原始的文件名
            String headSculptureDocumentName = file.getOriginalFilename();
            // 3 先截取原文件的文件名后缀
            String headSculptureSuffix = headSculptureDocumentName.substring(headSculptureDocumentName.lastIndexOf("."), headSculptureDocumentName.length());
//        获取新图片名与图片路径
            String pictureUrl = headSculptureUrlPrefix + headSculptureId + headSculptureSuffix;
//            新图像文件名
            String headSculptureNewDocumentName = headSculptureId + headSculptureSuffix;
//        图片储存
            File newFile = new File(pictureUrl);
            newFile.getParentFile().mkdir();
            file.transferTo(newFile);
            System.out.println("上传成功");


            userService.createUser(username, password, nickname, phone, headSculptureId, headSculptureNewDocumentName,personalIntroduction);
        }
        return "redirect:/";
    }

    //    用户信息编辑
    @RequestMapping(value = "/", method = RequestMethod.PUT)
    public String editUser(@RequestParam("file") MultipartFile file,
                             @RequestParam("username") String username,
                             @RequestParam("password") String password,
                             @RequestParam("nickname") String nickname,
                             @RequestParam("phone") int phone,
                             @RequestParam("personalIntroduction") String personalIntroduction,
                           HttpSession session

    ) throws IOException {
        if (session == null && null == file) {
            return "redirect:/";
        }else {
            int userId = Integer.parseInt(session.toString());
            User userByUserId = userService.getUserByUserId(userId);
//        图片id
            String headSculptureId = userByUserId.getHeadSculptureId();
//        图片路径前缀
            String headSculptureUrlPrefix = "D:/Syzygy/headsculpture";
//        获取图片类型
            // 2 获取原始的文件名
            String headSculptureDocumentName = file.getOriginalFilename();
            // 3 先截取原文件的文件名后缀
            String headSculptureSuffix = headSculptureDocumentName.substring(headSculptureDocumentName.lastIndexOf("."), headSculptureDocumentName.length());
//        获取新图片名与图片路径
            String pictureUrl = headSculptureUrlPrefix + headSculptureId + headSculptureSuffix;
//            新图像文件名
            String headSculptureNewDocumentName = headSculptureId + headSculptureSuffix;
//        图片储存
            File newFile = new File(pictureUrl);
            newFile.getParentFile().mkdir();
            file.transferTo(newFile);
            System.out.println("上传成功");


            userService.editUser(username, password, nickname, phone, headSculptureId, headSculptureNewDocumentName, personalIntroduction,userId);
        }
        return "redirect:/";
    }


    //    用户登录
    @RequestMapping(value = "/Login", method = RequestMethod.POST)
    public String getUserByUserUsernameAndPassword(Model model,
                                                   @RequestParam("username") String username,
                                                   @RequestParam("password") String password,
                                                   HttpSession session) {
        if (null != userService.getUserByUserUsernameAndPassword(username, password)) {
            // 将登录用户名写入会话
            int userId = userService.getUserByUserUsernameAndPassword(username, password).getUserId();
            session.setAttribute("userId", userId);
            // 删除会话里可能存在的登录错误提示信息
            if (session.getAttribute("loginMsg") != null) {
                session.removeAttribute("loginMsg");
            }
            return "redirect:/User/Homepage/" + userId; // 逻辑视图名
        } else {
            // 将登录错误信息写入
            model.addAttribute("loginMessageModel", "用户名或密码错误！");
            // 跳转到前台登录页面
            return "userLoginCard"; // 逻辑视图名
        }
    }


    //    用户登录退出
    @RequestMapping("/Logout")
    public String logout(HttpSession session) {
        // 删除会话里保存的用户名信息
        session.removeAttribute("userId");
        // 结束会话
        session.invalidate();
        return "redirect:/";
    }

    //    用户主页
    @RequestMapping("/Homepage/{userId}")
    public String userHomePage(@PathVariable int userId, Model model, HttpSession session) {
        List<Picture> picturesByUserId = pictureService.getPicturesByUserId(userId);
        String picturesByUserIdJSON = JSONArray.toJSONString(picturesByUserId);
        model.addAttribute("picturesByUserIdJSON", picturesByUserIdJSON);
        User userByUserId = userService.getUserByUserId(userId);
        model.addAttribute("userByUserId", userByUserId);
        String userByUserIdJSON = JSONArray.toJSONString(userByUserId);
        model.addAttribute("userByUserIdJSON", userByUserIdJSON);
        Object userIdSession = session.getAttribute("userId");
        model.addAttribute("userIdSession", userIdSession);
        return "userHomePage";
    }


    //    用户创作者中心
    @RequestMapping("/Manage")
    public String managePage(HttpSession session,Model model) {
        Object userIdSession = session.getAttribute("userId");
        if (userIdSession == null) {
            return "redirect:/";
        } else {
            int userId = Integer.parseInt(userIdSession.toString());
            List<Picture> picturesByUserId = pictureService.getPicturesByUserId(userId);
            String picturesByUserIdJSON = JSONArray.toJSONString(picturesByUserId);
            model.addAttribute("picturesByUserId",picturesByUserId);
            model.addAttribute("picturesByUserIdJSON",picturesByUserIdJSON);

            List<Type> allType = typeService.getAllType();
            String allTypeJSON = JSONArray.toJSONString(allType);
            model.addAttribute("allTypeJSON", allTypeJSON);

            User userByUserId = userService.getUserByUserId(userId);
            model.addAttribute("userByUserId", userByUserId);
            String userByUserIdJSON = JSONArray.toJSONString(userByUserId);
            model.addAttribute("userByUserIdJSON", userByUserIdJSON);

            model.addAttribute("userIdSession", userIdSession);

            return "userManagePage";

        }
    }

    @RequestMapping("/Edit")
    public String editCard(HttpSession session){
        if (session == null){
            return "redirect:/";
        }else {
            return "userEditCard";
        }

    }

}